package com.ym.student.system.controller;

import com.ym.student.system.entity.SysUser;
import com.ym.student.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class SysUserController {

    @Autowired
    private ISysUserService sysUserService;

    // 获取所有用户
    @GetMapping
    public List<SysUser> getAllUsers() {
        return sysUserService.list();
    }

    // 根据ID获取用户
    @GetMapping("/{id}")
    public SysUser getUserById(@PathVariable("id") Integer userId) {
        return sysUserService.getById(userId);
    }

    // 添加用户
    @PostMapping
    public boolean addUser(@RequestBody SysUser sysUser) {
        return sysUserService.save(sysUser);
    }

    // 更新用户
    @PutMapping("/{id}")
    public boolean updateUser(@PathVariable("id") Integer userId, @RequestBody SysUser sysUser) {
        sysUser.setUserId(userId); // 确保更新的是指定ID的用户
        return sysUserService.updateById(sysUser);
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable("id") Integer userId) {
        return sysUserService.removeById(userId);
    }

    // 新增：登录接口
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody SysUser user) {
        Map<String, Object> result = new HashMap<>();

        if (user.getUserName() == null || user.getPassword() == null) {
            result.put("success", false);
            result.put("message", "用户名或密码不能为空");
            return result;
        }

        // 查询用户是否存在
        SysUser dbUser = sysUserService.getByUserName(user.getUserName());

        if (dbUser == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return result;
        }

        if (!dbUser.getPassword().equals(user.getPassword())) {
            result.put("success", false);
            result.put("message", "密码错误");
            return result;
        }

        // 登录成功
        result.put("success", true);
        result.put("message", "登录成功");
        return result;
    }
}